<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/26
 * Time: 13:13
 */

namespace App\Http\Admin\Administration\Controllers;

use Framework\BaseClass\Http\Admin\Controller;
use App\Http\Admin\Administration\Models\Bill;
use Framework\Services\Excel\LaravelExcel\LaravelExcelService;

class BillController extends Controller
{
    /**
     * @Author pwj
     * 获取账单列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed
     */
    public function billList()
    {
        if (request()->isMethod('post')) {
            $page = request('pageCurrent');
            $pageSize = request('pageSize');
            $search = request()->except(['pageCurrent', 'pageSize']);
            $searchField = [];
            $searchRaw = "";
            if (!empty($search)) {
                if (isset($search['start_time'])) $searchField[] = ['created_at', ">=", strtotime($search['start_time'])];
                if (isset($search['end_time'])) $searchField[] = ['created_at', "<=", strtotime($search['end_time']) + 24 * 3600];
                unset($search['start_time']);
                unset($search['end_time']);
                if (!empty($search)) {
                    foreach ($search as $k => $v) {
                        if ($k == "status" && $v == 2) {
                            $searchRaw = time() . ">time AND amount_received<money";
                            continue;
                        }
                        if ($v || $v == "0") $searchField[] = [$k, 'like', '%' . $v . '%'];
                    }
                }
            }
            $companyId=session('current_operation_company_id',1);
            $searchField[]=['oa_company_id','=',$companyId];
            $bill = new Bill();
            return $bill->getBillList($page, $pageSize, $searchField, $searchRaw);
        } else {
            return $this->view('bill-list');
        }
    }

    /**
     * @Author pwj
     * 添加账单
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function billAdd()
    {
        try {
            if (request()->isMethod('post')) {
                $request = request()->all();
                $rules = [
                    'unit_price' => 'required|numeric',
                    'prior_number' => 'required|numeric',
                    'current_number' => 'required|numeric',
                    'money' => 'required|numeric',
                    'billing_date' => 'required|date',
                    'start_time' => 'required|date',
                    'type' => 'required',
                    'end_time' => 'required|date|after_or_equal:start_time',
                    'payment_time' => 'nullable|date',
                    'time' => 'required|date',
                    'status' => 'required'
                ];
                $validate = $this->validateRequestParameters($request, $rules, false);
                if ($validate) return $this->ajaxFail($validate);
                foreach ($request as $k => $v) {
                    if ($v == null) unset($request[$k]);
                }
                $request['start_time'] = strtotime($request['start_time']);
                $request['billing_date'] = strtotime($request['billing_date']);
                $request['end_time'] = strtotime($request['end_time']) + 24 * 3600 - 1;
                $request['time'] = strtotime($request['time']) + 24 * 3600 - 1;
                if (!empty($request['payment_time']) && strtotime($request['payment_time']) >= 0) $request['payment_time'] = strtotime($request['payment_time']);
                if ($request['start_time'] < 0 || $request['end_time'] < 0 || $request['time'] < 0 || $request['billing_date'] < 0) {
                    return $this->ajaxFail();
                }
                $electricity = new Bill();
                if ($electricity->insertBill($request)) return $this->ajaxSuccess();
                else return $this->ajaxFail();
            } else {
                $bill = new Bill();
                $companyInfo = $bill->getCompanyInfo(['id', 'name']);
                return $this->view('bill-add')
                    ->with('companyInfo', $companyInfo);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
    }

    /**
     * @Author pwj
     * 编辑账单
     * @return $this|\Illuminate\Http\JsonResponse
     */
    public function billEdit()
    {
        try {
            if (request()->isMethod('post')) {
                $request = request()->all();
                $rules = [
                    'unit_price' => 'required|numeric',
                    'prior_number' => 'required|numeric',
                    'current_number' => 'required|numeric',
                    'money' => 'required|numeric',
                    'start_time' => 'required|date',
                    'billing_date' => 'required|date',
                    'type' => 'required',
                    'end_time' => 'required|date|after_or_equal:start_time',
                    'payment_time' => 'nullable|date',
                    'time' => 'required|date',
                    'status' => 'required'
                ];
                $validate = $this->validateRequestParameters($request, $rules, false);
                if ($validate) return $this->ajaxFail($validate);
                foreach ($request as $k => $v) {
                    if ($v == null) $request[$k] = 0;
                }
                $request['start_time'] = strtotime($request['start_time']);
                $request['billing_date'] = strtotime($request['billing_date']);
                $request['end_time'] = strtotime($request['end_time']) + 24 * 3600 - 1;
                $request['time'] = strtotime($request['time']) + 24 * 3600 - 1;
                if (!empty($request['payment_time']) && strtotime($request['payment_time']) >= 0) $request['payment_time'] = strtotime($request['payment_time']);
                if ($request['start_time'] < 0 || $request['end_time'] < 0 || $request['time'] < 0 || $request['billing_date'] < 0) {
                    return $this->ajaxFail();
                }
                $electricity = new Bill();
                if ($electricity->updateBill($request)) return $this->ajaxSuccess();
                else return $this->ajaxFail();
            } else {
                $bill = new Bill();
                $billInfo = $bill->getBillById(request('id'));
                $companyInfo = $bill->getCompanyInfo(['id', 'name']);
                return $this->view('bill-edit')
                    ->with('companyInfo', $companyInfo)
                    ->with('billInfo', $billInfo);
            }
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
    }

    /**
     * @Author pwj
     * 获取excel插入数据库
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function billImport()
    {
        try {
            if (request()->isMethod('post')) {
                if (request()->hasFile('Bill') && request()->file('Bill')->isValid()) {
                    $bill = new Bill();
                    $electricityBill = request()->file('Bill');
                    $extension = $electricityBill->getClientOriginalExtension();
                    $storage_path = storage_path('/exports');//上传文件保存的路径
                    if (!file_exists($storage_path)) {//如果$storage_path（文件保存的目录）不存在
                        mkdir($storage_path, 0777, true);//创建一个目录
                    }
                    $filename = md5(ceil(microtime(true) * 1000)) . '.' . $extension; //确保文件不重名
                    if ($electricityBill->move($storage_path, $filename) == false) return xThrow(ERR_HTTP_FILE_UPLOAD);
                    $excel = new LaravelExcelService();
                    $data = $excel->import($filename)->getSheet(0)->toArray();
                    global $insertData, $error, $err_count, $success_count;
                    $error = $bill->importBill($data);
                    if ($error) {
                        request()->session()->put('error', $error);//将要导出的内容存入session 键值为error
                        $message = '本次共导入' . ($success_count + $err_count) . '条数据,其中失败' . $err_count . '条,以下为未插入数据序号<br>' . implode(",", $error);
                        return xThrow(ERR_ADMIN_EXCEL_ERROR, $message);
                    }
                    return $this->ajaxSuccess();
                } else return xThrow(ERR_HTTP_FILE_UPLOAD);
            } else return $this->view('bill-import');
        } catch (\DebugError $e) {
            return $this->ajaxFail($e->getMessage());
        }
    }

    /**
     * @Author pwj
     * 下载账单模板
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function billDownloadModel()
    {
        return response()->download(storage_path("template/bill/bill.xls"), "账单模板.xls");
    }
}